#import "MultiBabyViewController.h"
#import "MMScrollPresenter.h"
#import "DBManager.h"
#import "JsonUtil.h"
#import "PopUIManager.h"
#import "UserDao.h"
#import "NetWorkManager.h"
#import "AppDelegate.h"
#import "MainViewCreater.h"

@interface MultiBabyViewController ()
@property (weak, nonatomic) IBOutlet UIView *mainContent;
@property (weak, nonatomic) IBOutlet UIView *mmscrollPresenter;

@property (weak, nonatomic) IBOutlet UIButton *notMyBtn;

@property (weak, nonatomic) IBOutlet UIButton *isMyBtn;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UILabel *topTitle;

@property UIImageView *mountainImage;
@property UILabel *currentPage;
@property UILabel *nameTips;
@property UILabel *phoneTips;

@property NSUInteger current_baby;

@end

@implementation MultiBabyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    [self customView];
    [self initPresenter];
    _current_baby =0;
}

-(void)initPresenter
{
    
    NSUInteger width = APP_SCREEN_WIDTH -31*2;
    NSUInteger i=0;
    NSUInteger total = [_childArr count];
    //for (NSDictionary *dic in _childArr) {
    //    i++;
    //    NSString *avatar = [dic objectForKey:@"avatar"];
    //    NSString *avatar_url = [NSString stringWithFormat:@"%@%@",_avatar_header,avatar];
   //     NSString *phone = [dic objectForKey:@"phone"];
        _mountainImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"default_circle_icon"]];
        [_mountainImage setFrame:CGRectMake(width/2 -35, 13, 70, 70)];
        
        _currentPage = [[UILabel alloc]initWithFrame:CGRectMake(width/2-10, 89, 20, 20)];
        _currentPage.textAlignment = NSTextAlignmentCenter;
        _currentPage.textColor = UIColorMake(139, 131, 131);
        _currentPage.font = [UIFont systemFontOfSize:13];
    
        
        _nameTips = [[UILabel alloc]initWithFrame:CGRectMake(width/2-70, 152, 140, 30)];
        _nameTips.textColor = UIColorMake(34, 34, 34);
        _nameTips.textAlignment = NSTextAlignmentCenter;
        _nameTips.font = [UIFont systemFontOfSize:17];
        _nameTips.text = [NSString stringWithFormat:@"班级中已有“%@”",_babyName];
        
        _phoneTips = [[UILabel alloc]initWithFrame:CGRectMake(width/2-129, 180, 258, 28)];
        _phoneTips.textColor = UIColorMake(83, 80, 80);
        _phoneTips.textAlignment = NSTextAlignmentCenter;
        _phoneTips.font = [UIFont systemFontOfSize:15];
       // _phoneTips.text=[NSString stringWithFormat:@"（注册人手机号为%@）",phone];
        
        [_mmscrollPresenter addSubview:_mountainImage];
        [_mmscrollPresenter addSubview:_currentPage];
        [_mmscrollPresenter addSubview:_nameTips];
        [_mmscrollPresenter addSubview:_phoneTips];
        [self displayView:0];
    
    //}
   
}

-(void)displayView:(NSUInteger)item
{
    if(item>_childArr.count -1){
        return;
    }
    NSDictionary *dic = [_childArr objectAtIndex:_current_baby];
    NSString *avatar = [dic objectForKey:@"avatar"];
    NSString *avatar_url = [NSString stringWithFormat:@"%@%@",_avatar_header,avatar];
    NSString *phone = [dic objectForKey:@"phone"];
    _phoneTips.text=[NSString stringWithFormat:@"（注册人手机号为%@）",phone];
    _currentPage.text = [NSString stringWithFormat:@"%ld/%ld",_current_baby+1,[_childArr count]];
}

-(void)customView
{
  
    self.view.backgroundColor=[[UIColor blackColor] colorWithAlphaComponent:.6];
    
   self.mainContent.layer.shadowOpacity = 0.8;
    self.mainContent.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
    
    
    _mainContent.layer.cornerRadius = 5.0;
    _topView.backgroundColor = UIColorMake(243, 243, 243);
    _topTitle.textColor = UIColorMake(139, 131, 131);
    NSMutableAttributedString *tTitle = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"共出现%ld个重名！",_childArr.count] ];
    [tTitle addAttribute:NSForegroundColorAttributeName value:UIColorMake(241, 76, 92) range:NSMakeRange(3,1)];
    [_topTitle setAttributedText:tTitle];
    _isMyBtn.layer.cornerRadius = 5.0;
    _notMyBtn.layer.cornerRadius = 5.0;
    _isMyBtn.backgroundColor = UIColorMake(252, 74, 74);
    _notMyBtn.backgroundColor = UIColorMake(252, 74, 74);
    
}

- (void)showAnimate
{
    
    self.view.transform = CGAffineTransformMakeScale(1.3, 1.3);
    self.view.alpha = 0;
    [UIView animateWithDuration:.25 animations:^{
        self.view.alpha = 1;
        self.view.transform = CGAffineTransformMakeScale(1, 1);
    }];
}

- (void)removeAnimate
{
    [UIView animateWithDuration:.25 animations:^{
        self.view.transform = CGAffineTransformMakeScale(1.3, 1.3);
        self.view.alpha = 0.0;
    } completion:^(BOOL finished) {
        if (finished) {
            [self.view removeFromSuperview];
        }
    }];
}


- (void)showInView:(UIView *)aView animated:(BOOL)animated
{
    [aView addSubview:self.view];
    if (animated) {
        [self showAnimate];
    }
}

- (IBAction)clickNotMine:(id)sender {
    
    if ((_current_baby+1) < [_childArr count]) {  //继续查看下一个宝贝是不是自家的宝贝
        _current_baby++;
        [self displayView:_current_baby];
    }else{
        
        NSString* uid = [NSString stringWithFormat:@"%ld",[[UserDao getInstance]getUserId]];
        BabyInfo *baby = [[UserDao getInstance]getCurrentBaby];
        
        NSString *dataString = [JsonUtil convertDictionaryToJson:[[NSDictionary alloc]initWithObjectsAndKeys:uid, @"uid",_classCode,@"classcode",
                                                                  @(1),@"utype",[[UserDao getInstance]getAccessToken],@"token",@(_babyId),@"childid",@(2),@"checkname",nil]];
        
        
        PopUIManager *popUIMgr = [PopUIManager getInstanse];
        [popUIMgr showWaitingUI:self.view];
        
        [[NetWorkManager getInstanse] requestURLAsynMessage:BABY_JOIN_CLASS data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (connectionError) { //连接失败
                debugLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
                NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
                [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
            }else{//连接成功，判断是否有数据返回
                NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                NSLog(@"服务器返回StateCode:%ld", (long)responseCode);
                
                if (data) {
                    NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                    NSLog(@"数据字典: %@", dict);
                    
                    if ([[dict objectForKey:@"ret"] integerValue]== 1) {
                        //登录失败，弹窗提示
                        NSString *ret_msg;
                        switch ([[dict objectForKey:@"retCode"] integerValue]) {
                            case 1:{
                                ret_msg= @"SuccessJoin";
                                //加入班级成功~
                                NSString *fid = [dict objectForKey:@"fid"];
                                if(fid!=nil &&  fid!=[NSNull null]){
                                    NSDictionary *update_user = @{@"fid":fid,@"fcode":[dict objectForKey:@"invite_code"]};
                                    [[UserDao getInstance]updateUserInfo:update_user withReload:YES];
                                }
                                NSDictionary *classinfo = [dict objectForKey:@"classinfo"];
                                NSMutableDictionary *updateDict = [[NSMutableDictionary alloc]init];
                                [updateDict setObject:@([[classinfo objectForKey:@"id"] integerValue]) forKey:@"classid"];
                                [updateDict setObject:[classinfo objectForKey:@"name"] forKey:@"classname"];
                                [updateDict setObject:[classinfo objectForKey:@"schoolid"] forKey:@"schoolid"];
                                [updateDict setObject:[classinfo objectForKey:@"schoolname"] forKey:@"schoolname"];
                                [updateDict setObject:[classinfo objectForKey:@"kx_auth"] forKey:@"kx_auth"];
                                [[BabyDao getInstance]updateBabyInfo:updateDict withCid:baby.cid];
                                //更新数据
                                if(_add_baby){
                                    [self removeAnimate];
                                     ((AppDelegate*)[UIApplication sharedApplication].delegate).dyn_need_refresh = YES;
                                    [self.navigationController popToRootViewControllerAnimated:YES];
                                    return ;
                                }else{
                                    [self removeAnimate];                                     [self goInMain];
                                    return;
                                }
                                break;
                            }
                            case 10016:
                            {
                                
                                break;
                            }
                            case 2:{
                                ret_msg= @"宝贝信息不存在";
                                break;
                            }case 3:{
                                ret_msg= @"已经加入了班级，不能重复加入";
                                break;
                            }case 4:{
                                ret_msg= @"班级码不存在";
                                break;
                            }default:{
                                ret_msg= @"未知错误";
                                break;
                            }
                        }
                        if (![ret_msg isEqual:@"SuccessJoin"]) {
                            [popUIMgr popAlertView:nil title:@"提示" message:ret_msg cancelButtonTitle:@"确定"];
                        }
                    }else{
                        [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
                }
            }
            [popUIMgr removeWaitingUI];
        }];

    }
}

- (IBAction)clickIsMine:(id)sender {
    
    //MERGE BaBy
    NSDictionary *curr_dic = [_childArr objectAtIndex:_current_baby];
    
    NSString *dataString = [JsonUtil convertDictionaryToJson:[[NSDictionary alloc]initWithObjectsAndKeys:@([[UserDao getInstance] getUserId]), @"uid",@(1),@"utype",[[UserDao getInstance]getAccessToken],@"token",@(_babyId),@"my_bid",[curr_dic objectForKey:@"id"],@"dest_bid",nil]];
    
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    
    [[NetWorkManager getInstanse] requestURLAsynMessage:PARENT_MERGE_BABY data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) { //连接失败
            debugLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
        }else{//连接成功，判断是否有数据返回
            NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
            NSLog(@"服务器返回StateCode:%ld", (long)responseCode);
            
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                NSLog(@"数据字典: %@", dict);
                
                if ([[dict objectForKey:@"ret"] integerValue]== 1) {
                    //登录失败，弹窗提示
                    NSString *ret_msg;
                    switch ([[dict objectForKey:@"retCode"] integerValue]) {
                        case 1:{
                            ret_msg= @"SuccessJoin";
                            //合并成功，加入班级成功~~
                            NSString *fcode = [dict objectForKey:@"fcode"];
                            if(fcode!=nil &&  ![fcode isEqual:[NSNull null]]){
                                NSDictionary *update_user = @{@"fcode":[dict objectForKey:@"fcode"]};
                                [[UserDao getInstance]updateUserInfo:update_user withReload:YES];
                            }

                            [[BabyDao getInstance]deleteBabyById:_babyId];
                            
                            NSDictionary *babyinfo = [dict objectForKey:@"babyinfo"];
                            
                            [[BabyDao getInstance]saveBabyData:babyinfo];
                            NSUInteger cid = [[babyinfo objectForKey:@"cid"]integerValue];
                            BabyInfo *babyInfo = [[BabyDao getInstance]getBabyInfo:cid];
                            [[BabyDao getInstance]setCurrentBaby:babyInfo];
                            if(_add_baby){
                                [self removeAnimate];
                                 ((AppDelegate*)[UIApplication sharedApplication].delegate).dyn_need_refresh = YES;
                                UIViewController *parent = self.parentViewController;
                                [parent.navigationController popToRootViewControllerAnimated:YES];
                                
                            }else{
                                [self removeAnimate];
                                [self goInMain];
                                return;
                            }
                            //更新数据
                            break;
                        }
                            
                        case 10012:{
                            ret_msg= @"不是同一个家族，无权限合并其他家族的宝贝";
                            break;
                        }
                        default:{
                            ret_msg= @"未知错误";
                            break;
                        }
                    }
                    if (![ret_msg isEqual:@"SuccessJoin"]) {
                        [popUIMgr popAlertView:nil title:@"提示" message:ret_msg cancelButtonTitle:@"确定"];
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                }
            }else{
                [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
            }
        }
        [popUIMgr removeWaitingUI];
        [self removeAnimate];
    }];
   
}

-(void)goInMain
{
    UIViewController *mainViewController = [[MainViewCreater getInstance]createMainView];
       UIWindow *window = [[UIApplication sharedApplication]keyWindow];
    window.rootViewController = mainViewController;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
